package cn.itcast.netty.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        ChannelFuture channelFuture =new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                //1.连接到服务器，main异步调用，真正执行connect的是nio线程
                .connect(new InetSocketAddress("localhost",8080));


                //2.1 使用sync方法同步处理结果，阻塞住当前线程，等待nio线程执行完毕
              /* channelFuture.sync();
               Channel channel = channelFuture.channel();
               //发送数据
               channel.writeAndFlush("hello world!!!");*/

              //2.2使用addListener（回调对象）方法异步处理结果
              channelFuture.addListener(new ChannelFutureListener() {
                  @Override
                  public void operationComplete(ChannelFuture future) throws Exception {
                      Channel channel=future.channel();
                      log.debug("{}",channelFuture);
                      channel.writeAndFlush("hello world!!!");
                  }
              });

    }
}
